package com.sailor.grpc.demo.client.controller;

import com.alibaba.fastjson.JSONObject;
import com.sailor.demo.grpc.user.dto.AddUserRequest;
import com.sailor.demo.grpc.user.dto.SearchUserRequest;
import com.sailor.demo.grpc.user.dto.UserResponse;
import com.sailor.demo.grpc.user.service.UserGrpc;
import io.grpc.StatusRuntimeException;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class GrpcDemoController {

    @GrpcClient("userDemoClient")
    private UserGrpc.UserBlockingStub blockingStub;

    @GetMapping("/helloGrpc")
    public String helloGrpc(@RequestParam(value = "name", defaultValue = "World") String name) {
        log.info("开始helloGrpc");
        AddUserRequest request = AddUserRequest.newBuilder().setAddress("北京").setAge(26).setName("sailor").build();
        UserResponse response;
        try {
            response = blockingStub.add(request);
        } catch (StatusRuntimeException e) {
            log.error("RPC failed: " + e.getMessage(), e);
            throw e;
        }
        log.info("testAdd结果: " + response.getName());

        return JSONObject.toJSONString(response.getName());
    }

    @GetMapping("/listGrpc")
    public List<String> listGrpc(@RequestParam(value = "name", defaultValue = "World") String name) {
        log.info("开始 listGrpc");
        SearchUserRequest request = SearchUserRequest.newBuilder().setName(name).build();
        List<UserResponse> responseList = new ArrayList<>();
        try {
            Iterator<UserResponse> iterator = blockingStub.list(request);
            while (iterator.hasNext()){
                responseList.add(iterator.next());
            }
        } catch (StatusRuntimeException e) {
            log.error("RPC failed: " + e.getMessage(), e);
            throw e;
        }
        log.info("testAdd结果: " + responseList);

        return responseList.stream().map(e -> new String(e.toString().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)).collect(Collectors.toList());
    }
}
